﻿namespace Compass.Maui.ViewModels;

public partial class LoginPageViewModel : BaseViewModel
{
    private readonly ILoginService _loginService;
    public LoginPageViewModel(ILoginService loginService,IPreferenceService preferenceService)
    {
        _loginService = loginService;
        UserName = preferenceService.Get(Consts.UserName, "");
        Password=preferenceService.Get(Consts.Password, "123");
    }

    [ObservableProperty] private string userName;
    [ObservableProperty] private string password;

    [RelayCommand]
    private async Task LoginAsync()
    {
        await IsBusyFor(async () =>
        {
            var isAuthenticated = false;
            try
            {
                if (string.IsNullOrWhiteSpace(UserName) || string.IsNullOrWhiteSpace(Password)) return;

                isAuthenticated = await _loginService.LoginAsync(new UserDto()
                {
                    UserName = this.UserName,
                    Password = this.Password,
                });
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"[SignIn] Error signing in: {ex}");
            }

            if (isAuthenticated)
            {
                await Shell.Current.GoToAsync($"//{nameof(MainPage)}");
            }
        });
    }
}